package br.com.persistence;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.TransactionManager;

public class ConnectionManager {

	private static ThreadLocal<EntityManager> tredLocal = new ThreadLocal<EntityManager>();
	private static ThreadLocal<EntityTransaction> transactionLocal = new ThreadLocal<EntityTransaction>();
	
	public static EntityManager getEntityManager() {
		FacesContext fc = FacesContext.
				getCurrentInstance();
		ExternalContext ec = fc.
				getExternalContext();
		HttpServletRequest request = (HttpServletRequest)ec.
				getRequest();
		EntityManager entityManager = (EntityManager) request.
				getAttribute("EntityManager");
		return entityManager;
	
	}

	
	public static void commit() {
		EntityTransaction transaction = getTransaction();
		if (transaction.isActive()) {
			transaction.commit();
		}
		
	}

	public static EntityTransaction getTransaction() {
		EntityTransaction transactionManager = transactionLocal.get();
		if(transactionManager == null || !transactionManager.isActive()){
			transactionManager = getEntityManager().getTransaction();
		}
		return transactionManager;
	}
	
	public static void beginTransaction() {	
		getTransaction().begin();
	}

	public static void rollback() {
		EntityTransaction transaction = getTransaction();
		if (transaction.isActive()) {
			transaction.rollback();
		}
		
	}
	public static void close() {
		EntityManager entityManager = tredLocal.get();
		if (entityManager != null && entityManager.isOpen()) {
			entityManager.close();
		}
	}
}
